package com.tange.ai.iot.client.gnssa.lan

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.util.Consumer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.databinding.ActivityAddApScanBinding
import com.tange.ai.iot.client.gnssa.play.DeviceLiveActivity
import com.tange.base.toolkit.Tips
import com.tange.base.toolkit.mainHandler
import com.tange.base.ui.design.BasicDialogLoading
import com.tange.base.ui.design.BasicDialogRequest
import com.tange.feature.binding.connect.ap.DeviceBindingConnectionByAccessPoint
import com.tange.feature.binding.query.DeviceBindingQuery
import com.tange.feature.binding.search.DeviceBindingSearchAccessPoint
import com.tg.appcommon.android.TGLog

class LanApScanActivity: AppCompatActivity() {

    companion object {
        const val TAG = "BindingApScanActivity_"
    }

    private lateinit var binding: ActivityAddApScanBinding

    private lateinit var apSearch: DeviceBindingSearchAccessPoint

    private var apConnection: DeviceBindingConnectionByAccessPoint? = null

    private var bindingConfiguration = ""

    private var adapter: ApListAdapter? = null

    private var loading: BasicDialogLoading? = null

    private var bindingQuery: DeviceBindingQuery? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityAddApScanBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
        }

        com.tange.ai.iot.client.gnssa.utils.Utils.setStatusBar(this, Color.TRANSPARENT)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 100)
        }


        apSearch = DeviceBindingSearchAccessPoint(this) {
            TGLog.i(TAG, "[onSearched] $it")

            if (it.success) {
                adapter?.refreshApList(it.data)
            } else {
                binding.startScan.isEnabled = true
                Toast.makeText(this@LanApScanActivity, "扫描失败: ${it.message}", Toast.LENGTH_LONG).show()
            }
        }

        binding.startScan.setOnClickListener {
            binding.startScan.isEnabled = false
            apSearch.start()
        }

        adapter = ApListAdapter()
        adapter?.onSelected = Consumer<String> { connectAndSend(it) }

        binding.apList.adapter = adapter
        binding.apList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

        binding.apList.post {
            BasicDialogRequest(this).apply {
                setMessage("点击\"开始扫描\"以搜索附近的设备热点")
                setPositiveText("知道了")
                setPositiveOnClicked {
                    binding.startScan.isEnabled = true
                    dismiss()
                }
            }.show()
        }
    }

    private fun connectAndSend(apName: String) {

        loading?.dismiss()
        loading = BasicDialogLoading(this).apply {
            setMessage("尝试连接设备...")
        }
        loading?.show()

        if (apConnection != null) return

        apConnection = DeviceBindingConnectionByAccessPoint(this@LanApScanActivity, apName)
        apConnection?.connect(bindingConfiguration)  {
            loading?.dismiss()
            if (it.success) {
                Toast.makeText(this@LanApScanActivity, "连接成功，2s后跳转实时播放...", Toast.LENGTH_LONG).show()
                mainHandler().postDelayed({

                    // 从设备的AP名称中，解析出设备ID
                    // 注意：此处只是示例，要根据自己产品的实际情况调整
                    val deviceId = apName.replace("AICAM_", "")

                    DeviceLiveActivity.launchLanMode(this@LanApScanActivity, deviceId)
                    finish()
                }, 2000L)
            } else {
                Toast.makeText(this@LanApScanActivity, "连接失败 ${it.code}, ${it.message}", Toast.LENGTH_LONG).show()
            }
        }
        Tips.show("由于系统限制，你需要手动点击连接")
    }

    override fun onDestroy() {
        super.onDestroy()
        apSearch.stop()
        bindingQuery?.stop()
        apConnection?.destroy()
    }
}

class ApListAdapter : RecyclerView.Adapter<ViewHolder>() {
    private val apList: MutableList<String> = ArrayList()

    var onSelected: Consumer<String>? = null

    fun refreshApList(list: List<String>?) {
        apList.clear()
        list?.let { apList.addAll(it) }
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
        val view: View = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_scan_ap, viewGroup, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
        val apName = apList[position]
        viewHolder.textView.text = apName

        viewHolder.itemView.setOnClickListener { view: View ->
            onSelected?.accept(apName)
        }
    }

    override fun getItemCount(): Int {
        return apList.size
    }
}

class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {

    val textView: TextView

    init {
        textView = view.findViewById(R.id.ap_name)
    }
}